const marked = require('marked');

marked.setOptions({
  renderer: new marked.Renderer(),
  gfm: true,
  tables: true,
  breaks: false,
  pedantic: false,
  smartLists: true,
  sanitize: true,
  smartypants: false
});

function compiler (domList) {
  // for (let dom of domList) {
  //   const origin = filter(dom.innerHTML);
  //   dom.innerHTML = marked(origin);
  // }
  for (let key in domList) {
    if (domList[key].nodeType === 1) {
      const origin = filter(domList[key].innerHTML);
      // wrap with div (for layout)
      domList[key].innerHTML = '<div>' + marked(origin) + '</div>';
    }
  }
  return domList;
}

function filter (origin) {
  let tmp = origin;
  // trim
  tmp = tmp.trim();

  // blockquote
  tmp = tmp.replace(/\&gt;[\s]+/g, '> ');

  // more space before the new line
  const space = tmp.trim().match(/\n[ ]+/)
  if (space) {
    const rule = new RegExp(space[0], 'g');
    tmp = tmp.replace(rule, '\n');
  }

  return tmp;
}

module.exports = compiler;
